package com.sicheng.algorithm.node;

/**
 * @author zsc
 * @version 1.0
 * @date 2021/9/16 16:36
 */
public class EntryNodeOfLoop {
    public static void main(String[] args) {

        ListNode head = ListNode.initList(new int[]{1, 2, 3, 4, 5, 6});
        ListNode tail = ListNode.getTail(head);
        tail.next = head.next;

        System.out.println(entryNodeOfLoop(head));
    }

    public static ListNode entryNodeOfLoop(ListNode head) {
        if (head == null)
            return null;

        ListNode fast = head, slow = head;

        do {
            fast = fast.next.next;
            slow = slow.next;
        } while (fast != slow);

        fast = head;

        while (fast != slow) {
            fast = fast.next;
            slow = slow.next;
        }

        return fast;
    }
}
